<?php
namespace Home\Service;

class WechatService
{
    // 提现
    public function withdraw($withdraw_id)
    {
        if (!$withdraw_id) {
            return false;
        }

        $withdraw = M('withdraw')->find($withdraw_id);
        if (!$withdraw) {
            return false;
        }

        if ($withdraw['money'] < 1) {
            return false;
        }

        if ($withdraw['status'] != 1) {
            return false;
        }

        Vendor('Wechat/Payment');
        $payment = new \WechatPayment(C('WX_CONF'));
        $openid  = M('user')->where(['id' => $withdraw['user_id']])->getField('openid');
        $data    = $payment->transfers($openid, '零钱提现', $withdraw['order_no'], $withdraw['money']);

        if ($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {

            commit();
            $update = [
                'status'         => 2,
                'transaction_id' => $data['payment_no'],
            ];

            $result1 = M('withdraw')->where(['id' => $withdraw_id])->save($update);

            $result2 = D('Home/User', 'Service')->moneyLog($withdraw['user_id'], -$withdraw['money'], '零钱提现');

            if ($result1 && $result2) {
                commit();
                return true;
            } else {
                rollback();
                return fasle;
            }
            
        } else {
            return false;
        }

    }
}
